/*
 * Copyright (c) 2008-2014, RF-Embedded GmbH
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 *  1. Redistributions of source code must retain the above copyright notice, 
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice, 
 *     this list of conditions and the following disclaimer in the 
 *     documentation and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.rfe.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.rfe.device.IProtocolDeviceInterface;
import com.rfe.test.impl.TCPDevice;

public class MainProgram {

	/**
	 * Main function.
	 * 1. Selecting the right communication device
	 * 2. Selecting the type of the reader
	 * 3. Executing test functions
	 * @param args 		Arguments
	 */
	public static void main(String[] args) 
	{
		System.out.println("");
		System.out.println("=============================================================");
		System.out.println("|| Welcome to the RF-Embedded Open Source Protocol-Handler ||");
		System.out.println("=============================================================");

		
        // Create instance of test program
        TestProgram t = new TestProgramExtended();

        IProtocolDeviceInterface dev = null;

        try{
	        dev = t.getTestDevice();
	        if (dev == null)
	        {
	        	dev = getProtocolDevice();
	        	
	            if (dev == null)
	                return;
	        }
	
	        // Initialize test program
	        if (!t.init(dev))
	        {
	            return;
	        }
	
	        // Execute the tests
	        while (true)
	        {
	            if (t.exec() == false)
	                break;
	        }
	        
        } catch(IOException e)
        {
        	e.printStackTrace();
        	return;
        }

        dev.close();
	}

	/**
	 * Queries the communication device from the console.
	 * @return		The new instance of the communication device, null if none was selected
	 * @throws IOException
	 */
    static IProtocolDeviceInterface getProtocolDevice() throws IOException
    {
    	IProtocolDeviceInterface dev = null;

        // Get the serial device where the reader is connected to
        while (true)
        {

            System.out.println("\n\n");
            System.out.print("Select connection type: 's' for serial, 't' for tcp and 'q' for quit (s)> ");

            //  open up standard input
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            
            String connectionType = br.readLine();
            
            if(connectionType == null)
            	continue;

            if (connectionType.startsWith("s"))
            {
//                System.out.println("Available COM Ports: ");
//                // get all available port names
//                String[] theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();
//
//                // print them out with index to select
//                for (int i = 0; i < theSerialPortNames.Length; i++)
//                {
//                    System.out.println("\t [ {0:d} ]: {1}", i, theSerialPortNames[i]);
//                }
//                System.out.print("Please select the index of the COM Port of the reader (Enter 'q' to Quit): > ");
//                String port = Console.ReadLine();
//
//                if (port == "q")
//                    return false;
//
//                try
//                {
//                    int index = Convert.ToInt32(port);
//
//                    if (index < theSerialPortNames.Count())
//                    {
//                        // try to open the serial port
//                        dev = new Implementation.SerialDevice(theSerialPortNames[index]);
//                        if (dev.Open())
//                        {
//                            System.out.println("The COM-Port was open successfully");
//                            return true;
//                        }
//                        else
//                        {
//                            System.out.println("Could not open the COM-Port.");
//                        }
//                    }
//                    else
//                    {
//                        System.out.println("Index not in range.");
//                    }
//                }
//                catch (Exception)
//                {
//                    System.out.println("Could not convert input.");
//                }
            	System.out.println("Serial Ports are not available...");
            }
            //in case of tcp:
            else if (connectionType.startsWith("t") || connectionType.isEmpty())
            {
                System.out.print("Please type ip address (127.0.0.1)> ");
                String ipAddressString = br.readLine();

                System.out.print("Please type port (52475)> ");
                String portString = br.readLine();

                int port = 52475;
                if (!portString.isEmpty())
                    port = Integer.parseInt(portString);

                String ip = "127.0.0.1";
                if (!ipAddressString.isEmpty())
                    ip = ipAddressString;

                dev = new TCPDevice(ip, port);
                //try to connect over tcp
                if (dev.open())
                {
                    System.out.println("The TCP-Socket was open successfully");
                    return dev;
                }
                else
                {
                    System.out.println("Could not open the TCP-Socket.");
                }
            }
            else if (connectionType.startsWith("q"))
                return null;
            else
            {
                System.out.println("Unknown connection type >>" + connectionType + "<< entered.");
            }
        }
    }
}

